package org.itzheng.yuezhi.utils;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Title:FastJson封装的json解析工具
 * <br>
 * Description: <br>
 * Company: <br>
 *
 * @author ZhengYongdong
 * @email ItZheng@ZoHo.com
 * @date 2016/7/4 0004
 */
public class JsonUtils {
    private static final String TAG = "JsonUtils";

    /**
     * 对象转换成json字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        String json = null;
        try {
            json = JSON.toJSONString(obj);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
        } finally {
            return json;
        }
    }

    /**
     * json字符串转成对象
     *
     * @param str
     * @param type
     * @return
     */
    public static <T> T fromJson(String str, Type type) {
        T t = null;
        try {
            t = JSON.parseObject(str, type);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
        } finally {
            return t;
        }
    }

    /**
     * json字符串转成对象
     *
     * @param str
     * @param type
     * @return
     */
    public static <T> T fromJson(String str, Class<T> type) {
        T t = null;
        try {
            t = JSON.parseObject(str, type);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
        } finally {
            return t;
        }
    }

    /**
     * 将Map转化为Json
     *
     * @param map
     * @return String
     */
    public static <T> String mapToJson(Map<String, T> map) {
        String json = null;
        try {
            json = JSON.toJSONString(map);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
        } finally {
            return json;
        }
    }
}
